<template>
    <h1>购物车</h1>

    <button @click="addGoodsBtn">添加商品</button>
    <!-- 添加商品弹出框 -->
    <showmsg v-if="addGoodsFlag" @cancelBtn="cancelAddBtn" @okBtn="okAddBtn" />

    <!-- 商品列表 -->
    <ul class="list_ul">
        <li v-for="(item, index) in list" :key="index">
            商品名：{{ item.name }} --- 商品价格： {{ item.price }} --- <button @click="editBtn(index)">编辑</button> --- <button @click="delBtn(index)">删除</button>
        </li>
    </ul>

    <!-- 编辑商品弹框 -->
    <showmsg v-if="editGoodsFlag" @cancelBtn="cancelEditBtn" 
    @okBtn="okEditBtn" 
    />

    <!-- 删除确认框 -->
    <showmsg
        :isDel="true"
        v-if="delGoodsFlag"
        @cancelBtn="cancelDelBtn"
        @okBtn="okDelBtn"
    />
</template>

<script>
import goods from "./goods";
import showmsg from "./components/showmsg.vue"
export default {
    data() {
        return {
            list: [],
            addGoodsFlag: false,
            editGoodsFlag: false,
            editIndex: 0,
            delGoodsFlag: false,
            delIndex: 0,
        };
    },
    methods: {
        //获取商品
        async getGoods () {
            this.list = await goods.getGoods()
        },
        //添加按钮
        addGoodsBtn () {
            this.addGoodsFlag = true
        },
        //添加商品的取消按钮
        cancelAddBtn () {
            this.addGoodsFlag = false
        },
        //添加商品确定按钮
        async okAddBtn (goodsInfo) {
            await goods.createGoods(goodsInfo)
            await this.getGoods()
            this.addGoodsFlag = false
        },
        //点击编辑按钮
        editBtn(i) {
            this.editGoodsFlag = true
            this.editIndex = i
        },
        //编辑弹出框的取消按钮
        cancelEditBtn() {
            this.editGoodsFlag = false
        },
        //编辑弹出框确定按钮
        async okEditBtn(fromData) {
            //调用更新方法, 修改数据
            await goods.updateGoods(this.editIndex, fromData)
            //获取最新的数据, 更新页面
            await this.getGoods()
            //关闭弹出框
            this.cancelEditBtn()
        },
        //点击删除按钮
        delBtn(i) {
            this.delGoodsFlag = true
            this.delIndex = i
        },
        //删除弹框取消按钮
        cancelDelBtn() {
            this.delGoodsFlag = false
        },
        //删除弹框确定按钮
        async okDelBtn() {
            //调用删除方法, 删除对应的数据
            await goods.delGoods(this.delIndex)
            await this.getGoods()
            this.cancelDelBtn()
        }
    },
    mounted() {
        this.getGoods()
    },
    components: {
        showmsg,
    }
};
</script>

<style>
* {
    padding: 0;
    margin: 0;
}
html, body, #app {
    width: 100%;
    height: 100%;
}
</style>
